package com.ErpCoreWeb.Workflow;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ErpCoreModel.Base.CCompany;
import com.ErpCoreModel.Base.CRole;
import com.ErpCoreModel.Base.CUser;
import com.ErpCoreModel.Base.CUserInRole;
import com.ErpCoreModel.Framework.CBaseObject;
import com.ErpCoreModel.Framework.CBaseObjectMgr;
import com.ErpCoreModel.Framework.Util;
import com.ErpCoreModel.Workflow.CActives;
import com.ErpCoreModel.Workflow.CActivesDef;
import com.ErpCoreModel.Workflow.CWorkflow;
import com.ErpCoreModel.Workflow.CWorkflowDef;
import com.ErpCoreModel.Workflow.enumApprovalState;
import com.ErpCoreWeb.Common.EditObject;
import com.ErpCoreWeb.Common.Global;

/**
 * Servlet implementation class ViewWorkflow
 */
@WebServlet("/ViewWorkflow")
public class ViewWorkflow extends HttpServlet {
	private static final long serialVersionUID = 1L;

	HttpServletRequest request;
	HttpServletResponse response;

    public CBaseObjectMgr m_BaseObjectMgr = null;
    public CBaseObject m_BaseObject = null;
    public UUID m_guidParentId =Util.GetEmptyUUID();

    public CUser m_User = null;
    CCompany m_Company = null;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ViewWorkflow() {
        super();
        // TODO Auto-generated constructor stub
    }

    //初始化变量
    void initData()
    {
        if (request.getSession().getAttribute("User") == null)
        {
            try {
				response.sendRedirect("../Login.jsp");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return ;
        }
        m_User = (CUser)request.getSession().getAttribute("User");
        try {
	        m_Company = (CCompany)Global.GetCtx(this.getServletContext()).getCompanyMgr().Find(m_User.getB_Company_id());
	        

	        String TbCode = request.getParameter("TbCode");
	        String id = request.getParameter("id");
	        if (Global.IsNullParameter(TbCode)
	        		||Global.IsNullParameter(id))
	        {
	        	response.getWriter().print("数据不完整！");
	            response.getWriter().close();
	            return;
	        }

	        String ParentId = request.getParameter("ParentId");
	        if (!Global.IsNullParameter(ParentId))
	            m_guidParentId = Util.GetUUID(ParentId);


	        m_BaseObjectMgr = Global.GetCtx(this.getServletContext()).FindBaseObjectMgrCache(TbCode, m_guidParentId);
	        if (m_BaseObjectMgr == null)
	        {
	            m_BaseObjectMgr = new CBaseObjectMgr();
	            m_BaseObjectMgr.TbCode = TbCode;
	            m_BaseObjectMgr.Ctx = Global.GetCtx(this.getServletContext());
	        }
	        m_BaseObjectMgr.GetList();

	        m_BaseObject = m_BaseObjectMgr.Find(Util.GetUUID(id));

        } catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}
	void doProc(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{

		this.request=request;
		this.response=response;

		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");

		//初始化变量
	    initData();
	    //
        String Action = request.getParameter("Action");
        if (Action == null) Action = "";

        if (Action.equalsIgnoreCase("GetData"))
        {
        	GetData();
            return ;
        }
        else if (Action.equalsIgnoreCase("GetActivesData"))
        {
        	GetActivesData();
            return ;
        }
        else if (Action.equalsIgnoreCase("CancelWF"))
        {
        	CancelWF();
            return ;
        }
        else if (Action.equalsIgnoreCase("CanApproval"))
        {
        	CanApproval();
            return ;
        }
	}

    void GetData()
    {
        String sData = "";
        int iCount = 0;
        List<CWorkflow> lstWF = m_BaseObjectMgr.getWorkflowMgr().FindByRowid(m_BaseObject.getId());
        for (CWorkflow wf : lstWF)
        {
            CWorkflowDef WorkflowDef = wf.GetWorkflowDef();
            if (WorkflowDef == null)
                continue;
      		DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            sData += String.format("{ \"id\": \"%s\",\"Name\":\"%s\",\"Created\":\"%s\", \"State\":\"%s\"},"
                , wf.getId().toString()
                , WorkflowDef.getName()
                ,sdf.format(wf.getCreated())
                , wf.GetStateString());
            iCount++;
        }
        sData = "[" + sData + "]";
        String sJson = String.format("{\"Rows\":%s,\"Total\":\"%d\"}"
            , sData, iCount);

        try {
			response.getWriter().print(sJson);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

    void GetActivesData()
    {
        String WF_Workflow_id = request.getParameter("WF_Workflow_id");
        CWorkflow wf = (CWorkflow)m_BaseObjectMgr.getWorkflowMgr().Find(Util.GetUUID(WF_Workflow_id));

        String sData = "";
        CWorkflowDef WorkflowDef = wf.GetWorkflowDef();
        List<CBaseObject> lstObj = wf.getActivesMgr().GetList();
        for (CBaseObject obj : lstObj)
        {
            CActives Actives = (CActives)obj;

            CActivesDef ActivesDef = (CActivesDef)WorkflowDef.getActivesDefMgr().Find(Actives.getWF_ActivesDef_id());
            CUser User = (CUser)Global.GetCtx(this.getServletContext()).getUserMgr().Find(Actives.getB_User_id());
            CRole Role = (CRole)Global.GetCtx(this.getServletContext()).getCompanyMgr().FindTopCompany().getRoleMgr().Find(Actives.getB_Role_id());
            String UserName = "", RoleName = "";
            UserName = (User != null) ? User.getName() : "";
            RoleName = (Role != null) ? Role.getName() : "";

            sData += String.format("{ \"id\": \"%s\",\"Name\":\"%s\", \"Result\":\"%s\", \"Comment\":\"%s\", \"UserName\":\"%s\", \"RoleName\":\"%s\" },"
                , Actives.getId().toString()
                , ActivesDef.getName()
                , Actives.GetResultString()
                , Actives.getComment()
                , UserName
                , RoleName);
        }

        sData = "[" + sData + "]";
        String sJson = String.format("{\"Rows\":%s,\"Total\":\"%d\"}"
            , sData, lstObj.size());

        try {
			response.getWriter().print(sJson);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

    void CancelWF()
    {
		try {
			String WF_Workflow_id = request.getParameter("WF_Workflow_id");

			CWorkflow wf = (CWorkflow) m_BaseObjectMgr.getWorkflowMgr().Find(
					Util.GetUUID(WF_Workflow_id));
			// 只有启动者或管理员才能撤销
			if (!wf.getCreator().equals(m_User.getId())
					&& !m_User.IsRole("管理员")) {
				response.getWriter().print("没有权限撤销！");
				return;
			}

			if (!m_BaseObjectMgr.getWorkflowMgr().CancelWorkflow(wf)) {
				response.getWriter().print("撤销失败！");
				return;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

    void CanApproval()
    {
		try {
			String WF_Workflow_id = request.getParameter("WF_Workflow_id");

			CWorkflow wf = (CWorkflow) m_BaseObjectMgr.getWorkflowMgr().Find(
					Util.GetUUID(WF_Workflow_id));
			if (wf.getState() != enumApprovalState.Running) {
				response.getWriter().print("只有进行中的工作流才能审批！");
				return;
			}
			CActives Actives = wf.getActivesMgr().FindNotApproval();
			if (Actives == null) {
				response.getWriter().print("没有审批的活动！");
				return;
			}

			if (Actives.getAType().equals("按用户")) {
				if (!Actives.getB_User_id().equals(m_User.getId())) {
					response.getWriter().print("没有权限审批！");
					return;
				}
			} else // 按角色
			{
				CRole Role = (CRole) m_Company.getRoleMgr().Find(
						Actives.getB_Role_id());
				if (Role == null) {
					response.getWriter().print("角色不存在！");
					return;
				}
				CUserInRole UserInRole = Role.getUserInRoleMgr().FindByUserid(
						m_User.getId());
				if (UserInRole == null) {
					response.getWriter().print("没有权限审批！");
					return;
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

}
